import './style.css'

import Form from '../ui-components/Form/Form'
import FormItem from '../ui-components/Form/FormItem'
import Button from '../ui-components/Button/index'
import Tab from '../ui-components/Tab/index'
import Model from '../ui-components/Model'
import { useRef, useState } from 'react'
function Login (props) {
  const [tab, setTab] = useState(0)//tab页切换变量，默认展示索引值为0的页面
  const [flag, setFlag] = useState(false)//决定model弹窗是否展示
  const [message, setMessage] = useState('')//model弹窗中的提示语
  const [type, setType] = useState('')//model的展示类型
  const submitRef = useRef();//全局管理，用于调用Form子组件的函数
  const tabRef = useRef()//全局管理，用于调用Tab子组件的函数
  //登录函数
  const onSignIn = async () => {
    const { status, username } = await submitRef.current.onSignIn('/api1/sign_in');
    if (status === "new_user") {
      setMessage('未检测到用户，请先注册')
      setType('error')
      setFlag(true)
      setTimeout(() => {
        setFlag(false)
        setTab(1)
        tabRef.current.checkTab(1)
      }, 1200);
    }
    else if (status === "old_user") {
      sessionStorage.setItem("username", username);
      props.history.push({ pathname: '/cpo' })
    }
    else {
      //请求失败，弹窗提示重试
      setMessage('网络错误，请重试')
      setType('error')
      setFlag(true)
      setTimeout(() => {
        setFlag(false)
      }, 1200);
    }
  }
  //注册函数
  const onSignUp = async () => {
    const { status } = await submitRef.current.onSignUp('/api1/sign_up')
    if (status === 'success') {
      setMessage('注册成功，请登录')
      setType('success')
      setFlag(true)
      setTimeout(() => {
        setFlag(false)
        setTab(0)
        tabRef.current.checkTab(0)
      }, 1200);
    }
    else {
      //请求失败，弹窗提示重试
      setMessage('网络错误，请重试')
      setType('error')
      setFlag(true)
      setTimeout(() => {
        setFlag(false)
      }, 1200);
    }

  }
  //切换tab,默认传输点击的索引号
  const onCheckTab = (index) => {
    setTab(index)
  }
  //判断button组件是否展示
  const isDisabled = (state) => {
    let flag = true;
    const stateArray = Object.keys(state);
    for (let temp of stateArray) {
      flag &= !!state[temp]
    }
    return !flag;
  }
  //函数：正则匹配登录账号是字母与数字
  const onKeyUp = (onChange, e) => {
    const { target: { value } } = e
    let reg = /^[A-Za-z0-9]*$/
    if (reg.test(value)) {
      onChange(e)
    }
  }
  return (
    <div className='login-body'>
      <Model type={type} isShow={flag} message={message}></Model>
      <div className='login-container'>
        <Tab ref={tabRef} items={['登录', '注册']} onClick={onCheckTab}></Tab>
        <div className='login-content'>
          {!tab && (
            <>
              <div className='login-title'>登录</div>
              <div style={{ fontSize: '3rem', color: 'rgb(168, 156, 142)' }}>Lab-331</div>
              <Form style={{ width: "88%" }} ref={submitRef}>

                <FormItem name="account" title="账号" tipClass="login-tip" required>
                  {
                    ({ value, onChange, placeholder }) => <input
                      type="text"
                      className='login-input'
                      maxLength="8"
                      placeholder={placeholder}
                      value={value}
                      onChange={onKeyUp.bind(this, onChange)}
                    />
                  }

                </FormItem>

                <FormItem name="password" title="密码" tipClass="login-tip" required>
                  <input
                    type="password"
                    className='login-input'
                    maxLength="5" />
                </FormItem>

                <FormItem>
                  {
                    ({ state }) => {
                      return (
                        <>
                          <Button
                            title="登录"
                            onClick={onSignIn}
                            disabled={isDisabled(state)}
                            className={isDisabled(state) ?
                              'login-button login-disabled' :
                              'login-button'}></Button>
                        </>
                      )
                    }
                  }
                </FormItem>
              </Form>
            </>
          )
          }
          {!!tab && (
            <>
              <div className='login-title'>注册</div>
              <div style={{ fontSize: '3rem', color: 'rgb(168, 156, 142)' }}>Lab-331</div>

              <Form style={{ width: "88%" }} ref={submitRef}>

                <FormItem name="username" title="用户名" tipClass="login-tip" required>

                  <input
                    type="text"
                    className='login-input'
                    maxLength="8" />

                </FormItem>

                <FormItem name="account" title="账号" tipClass="login-tip" required>
                  {
                    ({ value, onChange, placeholder }) => <input
                      type="text"
                      className='login-input'
                      maxLength="8"
                      placeholder={placeholder}
                      value={value}
                      onChange={onKeyUp.bind(this, onChange)}
                    />
                  }
                </FormItem>

                <FormItem name="password" title="密码" tipClass="login-tip" required>
                  <input
                    type="password"
                    className='login-input'
                    maxLength="10" />
                </FormItem>

                <FormItem>
                  {
                    ({ state }) => {
                      return (
                        <>
                          <Button
                            title="注册"
                            onClick={onSignUp}
                            disabled={isDisabled(state)}
                            className={isDisabled(state) ?
                              'login-button login-disabled' :
                              'login-button'}></Button>
                        </>
                      )
                    }
                  }
                </FormItem>
              </Form>
            </>
          )
          }
        </div>
      </div>
    </div>

  )
}
export default Login;